package com.gxa.zuul.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.zuul.pojo.YongHu;
import com.gxa.zuul.service.YongHuService;
import com.gxa.zuul.token.SkipJWT;
import com.gxa.zuul.util.JwtUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author thinknovo
 * @version 1.0
 * @description JwtAuthenticationInterceptor.java
 */
public class JwtAuthenticationInterceptor implements HandlerInterceptor {
    @Resource
    private YongHuService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // preHandle返回true代表放行用户的请求，返回false代表拦截用户的请求
        System.out.println("------------preHandle--------------");
        // 从请求头中取出 token  这里需要和前端约定好把jwt放到请求头一个叫token的地方
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;   // 请求页面，返回true，代表放行
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();   // POST GET...
        System.out.println("method=" + method);
        //检查是否有SkipJWT注解，有则跳过认证
        if (method.isAnnotationPresent(SkipJWT.class)) {
            SkipJWT skipJWT = method.getAnnotation(SkipJWT.class);   // 获取指定方法头上的指定名称的注解对象
            if (skipJWT.required()) {   // required方法默认返回true
                return true;            // 放行
            }
        }
        //默认全部检查
        else {
            System.out.println("被jwt拦截需要验证  url=" + httpServletRequest.getRequestURL());
            // 执行认证
            if (token == null) {
                System.out.println("用户没有token，无法执行后续任务");
                httpServletResponse.setContentType("application/json;charset=utf-8");
                Map<String, Object> map = new HashMap<>();
                map.put("code", 500);
                map.put("msg", "用户未登录，无法使用此功能");

                httpServletResponse.getWriter().print(new ObjectMapper().writeValueAsString(map));
                return false;
            }

            // 获取 token 中的 username
            // 用户的id肯定会封存在token中
            String userId = JwtUtils.getAudience(token);   // token解码出来的第一部分是用户id
            System.out.println("userId=" + userId);
            if(userId == null) {
                System.out.println("用户没有token，并且也没有获取用户的主键，无法执行后续任务");
                return false;
            }

            //找找看是否有这个user   因为我们需要检查用户是否存在
            YongHu user = userService.getUser(userId);  // 这里目前修改为用户名验证

            if (user == null) {
                System.out.println("没有查询到对应的用户，无法执行后续任务");
                return false;
            }

            // 验证 token
            JwtUtils.verifyToken(token, userId);

            //获取载荷内容
            String userName = JwtUtils.getClaimByName(token, "userName").asString();
            String realName = JwtUtils.getClaimByName(token, "realName").asString();
            System.out.println("username=" + userName);
            System.out.println("realName=" + realName);

            //放入attribute以便后面调用
            httpServletRequest.setAttribute("userName", userName);
            httpServletRequest.setAttribute("realName", realName);

            return true;

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
